import os
import time
from ..crud.ppt_crud import create_ppt as create_ppt_db
from dotenv import load_dotenv
from fastapi import APIRouter, Depends
from pydantic import BaseModel,Field
from typing import Optional

from ..crud.user_crud import get_user_by_name
from ..models.ai_models.pptPart_api import run_coze_workflow2,run_coze_workflow1,device
import json
from ..utils.ppt_tools import download_ppt
from ..utils.jwt_handler import get_username
from sqlalchemy.orm import Session
from ..database.db import get_db

from ..redisbase.redis_test import user_info_init
from ..redisbase.redis_operations import set_hash_data,get_hash_data,get_hash_field

ppt_routers=APIRouter(prefix="/ppt", tags=["ppt"])

@ppt_routers.get("/")
async def hello_ppt():
    return {
        "code":200,
        "message":"hello ppt"
    }
load_dotenv()
API_TOKEN=os.getenv("API_TOKEN")
WORKFLOW_ID1 = "7524165514211541002"
WORKFLOW_ID2 = "7524182748136177664"



class PPTCreate(BaseModel):
    # ppt_name: str = Field(..., description="PPT 文件名称")
    topic: str = Field(..., description="PPT 主题")
    template_style: Optional[str] = Field(None, description="PPT 模板风格（可选）")
@ppt_routers.post("/choose-item")
async def create_ppt(params: PPTCreate,username: str = Depends(get_username)):
    topic = params.topic
    template_style = params.template_style
    result = run_coze_workflow1(workflow_id=WORKFLOW_ID1, api_token=API_TOKEN,
                                      user_input1=topic, user_input2=template_style)

    outline = json.loads(result).get("outline")
    themes = json.loads(result).get("theme")

    # print(outline)
    # print("outline",outline)
    # print("themes",themes)
    return {
        "code":200,
        "message":"success",
        "data":{
            "themes":themes,
            "outline":outline
        }
    }


class PPTGenerate(BaseModel):
    theme_id: int = Field(..., description="主题id")
    ppt_name: str = Field(..., description="PPT 文件名称")
    outline: dict

@ppt_routers.post("/generate-ppt")
async def generate_ppt(params: PPTGenerate,username: str = Depends(get_username),db: Session = Depends(get_db)):

    user = get_user_by_name(db, username).as_dict()
    user_id = user["id"]
    username = user["username"]
    current_date = time.strftime("%Y-%m-%d", time.localtime())
    user_info_init(user_id, username, current_date)
    new_video_quantity = int(get_hash_field(user_id, "ppt_quantity")) + 1
    user_info = get_hash_data(user_id)
    user_info["ppt_quantity"] = str(new_video_quantity)
    set_hash_data(user_id, user_info)

    theme_id = params.theme_id
    ppt_name = params.ppt_name
    outline = params.outline

    user=get_user_by_name(db,username)
    # print(outline)

    result = run_coze_workflow2(workflow_id=WORKFLOW_ID2, api_token=API_TOKEN, outline=outline, user_input3=theme_id)

    result=json.loads(result)
    ppt_url=result.get("output")

    load_dotenv()
    SOURCES_PATH=os.getenv("SOURCES_PATH")
    print("SOURCES_PATH",SOURCES_PATH)

    ppt_hou_url = "sources/ppts/download/" + f"{ppt_name}.ppt"

    path = os.path.join(SOURCES_PATH, ppt_hou_url)
    download_ppt(ppt_url, path)
    ppt_all_name=f"{ppt_name}.ppt"
    ppt_db=create_ppt_db(db,ppt_all_name,ppt_hou_url)




    return {
        "code":200,
        "message":"success",
        "data":{
            "ppt_url":ppt_hou_url,
            "ppt_item":ppt_db.as_dict()
        }
    }
#     return {
#   "code": 200,
#   "message": "success",
#   "data": {
#     "ppt_url": "sources/ppts/download/strisadfsang.ppt",
#     "ppt_item": {
#       "id": 12,
#       "name": "strisadfsang",
#       "path": "sources/ppts/download/strisadfsang.ppt"
#     }
#   }
# }

# @ppt_routers.pu